package ru.aslanov.schedule.server;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 18, 2010 3:58:30 PM
 *
 * @author Sergey Aslanov
 */
public class ServiceFactory {
    private static final Logger log = Logger.getLogger(ServiceFactory.class.getName());
    
    static final Map<String, AbstractService> SERVICE_MAP = new HashMap<String, AbstractService>();

    public static void dispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        final String[] strings = request.getRequestURI().split("/");
        String dataSource = strings[strings.length - 2];
        String operation = strings[strings.length - 1];

        log.fine(dataSource + "." + operation + " START");

        getService(dataSource).service(OperationEnum.valueOf(operation), request, response);

        log.fine(dataSource + "." + operation + " END");
    }

    static AbstractService getService(String dataSource) {
        AbstractService service = SERVICE_MAP.get(dataSource);
        if (service == null) {
            try {
                service = (AbstractService)
                        Class.forName("ru.aslanov.schedule.server.services." + dataSource + "Service").newInstance();
                SERVICE_MAP.put(dataSource, service);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return service;
    }
}
